<template>
  <!-- 内容 -->
  <div class="main">
    <div class="container pl-5 pr-5 pt-3 pb-3 mt-3 mb-3">
      <form class="mt-5" @submit.prevent="forget">
        <div class="form-group row">
          <label for="your-email" class="col-sm-2 col-form-label text-right">邮箱:</label>
          <div class="col-sm-10">
            <input type="email" class="form-control" id="your-email" placeholder="请输入您的邮箱!" required v-model="forgetForm.email">
            <div class="invalid-feedback">
              {{ errorMsg.emailMsg }}
            </div>
          </div>
        </div>
        <div class="form-group row mt-4">
          <label for="verifycode" class="col-sm-2 col-form-label text-right">验证码:</label>
          <div class="col-sm-6">
            <input type="text" class="form-control" id="verifycode" placeholder="请输入验证码!" v-model="forgetForm.code">
            <div class="invalid-feedback">
              {{ errorMsg.codeMsg }}
            </div>
          </div>
          <div class="col-sm-4">
            <a href="#" class="btn btn-info form-control" @click="sendCode">获取验证码</a>
          </div>
        </div>
        <div class="form-group row mt-4">
          <label for="your-password" class="col-sm-2 col-form-label text-right">新密码:</label>
          <div class="col-sm-10">
            <input type="password" class="form-control" id="your-password" placeholder="请输入新的密码!" required v-model="forgetForm.password">
            <div class="invalid-feedback">
              {{ errorMsg.passwordMsg }}
            </div>
          </div>
        </div>
        <div class="form-group row mt-4">
          <div class="col-sm-2"></div>
          <div class="col-sm-10 text-center">
            <button type="submit" class="btn btn-info text-white form-control">重置密码</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import User from '@/api/user'
import router from '@/router'

const forgetForm = ref({
  email: '',
  code: '',
  password: ''
})

const errorMsg = ref({
  emailMsg: '',
  codeMsg: '',
  passwordMsg: '',
})

const sendCode = async () => {
  await User.sendCode(forgetForm.value.email)
}

const forget = async () => {
  await User.forget(forgetForm.value.email, forgetForm.value.code, forgetForm.value.password).then((res) => {
    if (Object.keys(res).length > 0) {
      // 重置密码失败，显示错误信息
      console.log(res)
      errorMsg.value.emailMsg = res.emailMsg ?? ''
      errorMsg.value.codeMsg = res.codeMsg ?? ''
      errorMsg.value.passwordMsg = res.passwordMsg ?? ''
    } else {
      // 跳转到登录页
      router.push('login')
    }
  })
}
</script>
